$(function () {
    $.ajax({
        type: 'POST',
        url: '/area/getAreaList',
        async: false,
        data: {},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
            var level1AreaList = result.data.areaList;
            console.log(level1AreaList);
            var dataStr;
            if (level1AreaList.length>0){
                //dataStr = "";
                dataStr= '{ "title": "'+ result.data.companyName+'" ,"id": "","children":[';
            for (var i=0;i<level1AreaList.length;i++){
                dataStr += '{ "title": "' + level1AreaList[i].name + '" ,"id": "' +'**'+ level1AreaList[i].id  + '"';
                var sonAreaList =  level1AreaList[i].sonAreaList;
                if (sonAreaList.length>0 ){
                    dataStr +=',"children":[';
                    for (var j=0;j<sonAreaList.length;j++){
                        dataStr += '{ "title": "' + sonAreaList[j].name + '" ,"id": "**' +level1AreaList[i].id+"--"+sonAreaList[j].id  + '"';
                        var sonAreaList2 = sonAreaList[j].sonAreaList;
                        if (sonAreaList2.length>0){
                            dataStr +=',"children":[';
                            for (var k=0;k<sonAreaList2.length;k++){
                                dataStr += '{ "title": "' + sonAreaList2[k].name + '" ,"id": "**' +level1AreaList[i].id+"--"+sonAreaList[j].id +">>"+ sonAreaList2[k].id  + '"},';
                            }
                            dataStr = dataStr.substring(0, dataStr.length - 1);
                            dataStr +=']';
                        }
                        dataStr +='},'
                    }
                    dataStr = dataStr.substring(0, dataStr.length - 1);
                    dataStr +=']';

                }
                dataStr +='},'
                }
                dataStr = dataStr.substring(0, dataStr.length - 1);
                dataStr +=']}'
                console.log(dataStr)
            }else{
                dataStr ='{}'
            }
            var obj_groups = JSON.parse("["+dataStr+"]");
                layui.use(['tree', 'util'], function() {
                    var tree = layui.tree
                        , layer = layui.layer
                        , util = layui.util
                        , data1 =obj_groups
                    //常规用法
                    tree.render({
                        elem: '#test1' //默认是点击节点可进行收缩
                        , data: data1
                        ,click: function(obj) {
                            searchArea(obj.data.id);
                        }
                    });
                });

            //"},"
               }else{
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });
searchArea("");

});
function searchArea(searchId) {

    layui.use('table', function(){
        var table = layui.table;

        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            ,url: "/area/searchArea?searchId="+searchId
            ,cols: [[
                // {field:'id', title: 'ID', width:100, }
                {field:'id', title: '序号', width:100,}
                ,{field:'areaIds', title: '编号', width:100,}
                ,{field:'areaMsg', title: '区域信息', width:300}
                ,{field:'areaName', title: '区域名称', width:400}
                ,{field:'createTime', title: '创建时间', width:200}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:250}
            ]]
            ,id: 'testReload'
            ,page: true
            ,height: 650
            ,response: {
                statusCode: 666 //规定成功的状态码，默认：0
            }
            // ,even:true //每行条纹
            ,limits: [10,15,20,25,30]
            ,limit: 10 //每页默认显示的数量
            ,toolbar:'#toolbarDemo'  //导出打印
            ,parseData:function (res) {
                console.log(res);
                return{
                    "code":res.code,
                    "msg":res.msg,
                    "count":res.data.areaResponseList.length,
                    "data":res.data.areaResponseList1
                };
            }
            , done: function(res, curr, count){
                $("[data-field='areaIds']").css('display','none');
            }

        });

        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload');
                //执行重载
                table.reload('testReload', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                            searchName: demoReload.val()
                    }
                });
            }
        };

        $('.layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        table.on('tool(user)', function(obj){
            var id=obj.data['areaIds'];
            var layer;
            layui.use(['layer', 'form'], function(){
                layer = layui.layer
            });

            if(obj.event === 'edit'){
                updateArea(obj);
            }
            if(obj.event === 'del'){
                layer.confirm('确定要删除该区域信息吗？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        type: 'POST',
                        url: '/area/delArea',
                        async: false,
                        data: {"id":id},
                        dataType: 'json',
                        success: function (result) {
                            if (result.code==666){
                                layer.alert('删除成功', {icon: 1},function (index) {
                                    layer.close(index);
                                    window.location.reload()
                                });

                            }else{
                                layer.alert('删除失败', {icon: 2},function (index) {
                                    layer.close(index);
                                    window.location.reload()
                                });
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            if (XMLHttpRequest.status==555){
                                var layer;
                                layui.use(['layer', 'form'], function(){
                                    layer = layui.layer
                                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                                        //do something
                                        layer.close(index);
                                        top.location.href="/login";
                                    });

                                });

                            }else{
                                var layer;
                                layui.use(['layer', 'form'], function(){
                                    layer = layui.layer
                                    layer.alert('页面加载失败',{icon:7}, function(index){
                                        //do something
                                        layer.close(index);
                                    });
                                });
                            }
                        },
                    });

                }, function(){

                });

            }
        });

    });
}
function updateArea(obj) {
    console.log(obj.data);
    var areaIds = obj.data.areaIds;
    var areaName = obj.data.areaName;
    var level1Area="",level2Area="",level3Area="";
    var level1val="readonly",level2val="readonly",level3val="readonly";
    var areas = areaName.split(">");
    if(areas.length>0){
        level1Area=areas[0];
        level1val="";
    }
    if(areas.length>1){
        level2Area=areas[1];
        level1val="readonly";
        level2val="";
    }
    if(areas.length>2){
        level3Area=areas[2];
        level2val="readonly";
        level3val="";
    }
    var layer;
    layui.use(['layer', 'form'], function(){
        layer = layui.layer
    });
//页面层
    layer.open({
        type: 1,
        //skin: 'layui-layer-rim', //加上边框
        area: ['600px', '230px'], //宽高
        content: '<div class="layui-form-item" style="position: relative;top: -20px;left: 6px;margin-bottom: 0px;margin: 52px;">\n' +
            '        <label class="layui-form-label" style="width: 60px">区域</label>\n' +
            '        <div class="layui-input-inline" style="width: 120px">\n' +
            '            <input type="text" name="areaIdsModify" hidden lay-verify="required" value="'+areaIds+'"  autocomplete="off" class="layui-input">\n' +
            '            <input type="text" name="level1AreaModify" '+level1val+'  lay-verify="required" value="'+level1Area+'"  autocomplete="off" class="layui-input">\n' +
            '        </div>\n' +
            '\n' +
            '        <div class="layui-input-inline" style="width: 120px">\n' +
            '            <span class="area-span">-</span>\n' +
            '            <input type="text" name="level2AreaModify" '+level2val+'  lay-verify="required" value="'+level2Area+'" autocomplete="off" class="layui-input">\n' +
            '        </div>\n' +
            '\n' +
            '        <div class="layui-input-inline" style="width: 120px">\n' +
            '            <span class="area-span">-</span>\n' +
            '            <input type="text" name="level3AreaModify" '+level3val+' lay-verify="required" value="'+level3Area+'"  autocomplete="off" class="layui-input">\n' +
            '        </div>\n' +
            '    </div>' +
            ' <div style="position: relative;width: 200px;left: 32%;top: -18%;">\n' +
            '    <button type="button" class="layui-btn" onclick="modifyArea();">确&nbsp;&nbsp;&nbsp;&nbsp;认</button>' +
            '    <button type="button" class="layui-btn layui-btn-primary" onclick="calloff();">取&nbsp;&nbsp;&nbsp;&nbsp;消</button>\n' +
            '</div>'
    });

}
function modifyArea() {
    var areaIds = $("input[name='areaIdsModify']").val();
    var level1Area = $("input[name='level1AreaModify']").val();
    var level2Area = $("input[name='level2AreaModify']").val();
    var level3Area = $("input[name='level3AreaModify']").val();
    var areaType,areaName,areaId;
    if (areaIds.indexOf(">>")!==-1){
        areaType="3";
        areaId=areaIds.split(">>")[1];
        areaName=level3Area;
    }else if(areaIds.indexOf("--")!==-1){
        areaType="2";
        areaId=areaIds.split("--")[1];
        areaName=level2Area
    }else{
        areaType="1";
        areaId=areaIds.replace("**","");
        areaName=level1Area;
    }
    //console.log(areaId+"---"+areaType+"----"+areaName)
    $.ajax({
        type: 'POST',
        url: '/area/modifyArea',
        async: false,
        data: {"areaName":areaName,"areaType":areaType,"areaId":areaId},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
                layer.alert('修改成功', {icon: 1},function (index) {
                    layer.close(index);
                    window.location.reload()
                });
            }else{
                layer.alert('修改失败', {icon: 2},function (index) {
                    layer.close(index);
                    window.location.reload()
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });

}
function addArea() {
    var level1Area = $("input[name='level1AreaAdd']").val();
    var level2Area = $("input[name='level2AreaAdd']").val();
    var level3Area = $("input[name='level3AreaAdd']").val();
    $.ajax({
        type: 'POST',
        url: '/area/addArea',
        async: false,
        data: {"level1Area":level1Area,"level2Area":level2Area,"level3Area":level3Area},
        dataType: 'json',
        success: function (result) {
            if (result.code==666){
                layer.alert('添加成功', {icon: 1},function (index) {
                    layer.close(index);
                    window.location.reload()
                });
            }else{
                layer.alert('添加失败', {icon: 2},function (index) {
                    layer.close(index);
                    window.location.reload()
                });
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status==555){
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('未登录,请登录后操作',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                        top.location.href="/login";
                    });
                });
            }else{
                var layer;
                layui.use(['layer', 'form'], function(){
                    layer = layui.layer
                    layer.alert('页面加载失败',{icon:7}, function(index){
                        //do something
                        layer.close(index);
                    });
                });
            }
        },
    });


}
$("#add").click(function () {
    var layer;
    layui.use(['layer', 'form'], function(){
        layer = layui.layer
    });
//页面层
    layer.open({
        type: 1,
        //skin: 'layui-layer-rim', //加上边框
        area: ['600px', '230px'], //宽高
        content: '<div class="layui-form-item" style="position: relative;top: -20px;left: 6px;margin-bottom: 0px;margin: 52px;">\n' +
            '        <label class="layui-form-label" style="width: 60px">区域</label>\n' +
            '        <div class="layui-input-inline" style="width: 120px;background: yellow;" >\n' +
            '            <input type="text" name="level1AreaAdd"  lay-verify="required"   autocomplete="off" class="layui-input" placeholder="x号楼" >\n' +
            '        </div>\n' +
            '\n' +
            '        <div class="layui-input-inline" style="width: 120px">\n' +
            '            <span class="area-span">-</span>\n' +
            '            <input type="text" name="level2AreaAdd"  lay-verify="required" autocomplete="off" class="layui-input" placeholder="x单元">\n' +
            '        </div>\n' +
            '\n' +
            '        <div class="layui-input-inline" style="width: 120px">\n' +
            '            <span class="area-span">-</span>\n' +
            '            <input type="text" name="level3AreaAdd" lay-verify="required"   autocomplete="off" class="layui-input" placeholder="x室">\n' +
            '        </div>\n' +
            '    </div>' +
            ' <div style="position: relative;width: 200px;left: 32%;top: -18%;">\n' +
            '    <button type="button" class="layui-btn" onclick="addArea();">添&nbsp;&nbsp;&nbsp;&nbsp;加</button>' +
            '    <button type="button" class="layui-btn layui-btn-primary"onclick="calloff();">取&nbsp;&nbsp;&nbsp;&nbsp;消</button>\n' +
            '</div>'
    });
});
function calloff() {
    layer.closeAll();
}